<?php

/**
 * 邮件送队定时发送列功能
 *
 * @author libaoling
 * @time 2014-8-27
 */
class Mail_queueApp extends QueueApp
{
    public function __construct()
    {
        $this->lockFile = $this->getTempDir() . "/mail_queue_send.lock";
        parent::__construct();
    }
    
    public function index()
    {
        $model_mailqueue =& m('mailqueue');
        //清除发送N次错误和过期的邮件
        $model_mailqueue->clear();
        
        /* 取出待要发送的邮件 */
        $mails  = $model_mailqueue->find(array(
            'conditions'    => 'status > 1',
            'order'         =>  'status ASC, priority DESC, err_num ASC, add_time DESC',
            'limit'         => $this->limit,
        ));
            
        if ($mails) 
        {
            //发送前文件上锁  
            $this->lockUp();
            
            /* 获取邮件发送接口 */
            $mailer =& get_mailer();
            foreach ($mails as $v)
            {
                $result = $mailer->send($v['mail_to'], addslashes($v['mail_subject']), addslashes($v['mail_body']), $v['mail_encoding'], 1);
                if($result)
                {
                    $model_mailqueue->edit($v['queue_id'], "status = 1");
                }else
                {
                    $model_mailqueue->edit($v['queue_id'], "err_num = err_num + 1, status = 3");
                }
            }
            //发送完文件解锁
            $this->unLock();
        }
        
        $this->log('mail_queue_send');
    }
    
    /**
     * 记录运行日志
     *
     * @param $file_name
     */
    public function log($file_name = '')
    {
        if(empty($file_name))
            return;
        $content = "\r";
        $content .= date('Y-m-d H:i:s'). "\r\n";		
        $path_root = ROOT_PATH.'/log/tasks_log';//绝对路径
        ecm_mkdir($path_root);
        $file = $path_root.'/'.$file_name.'.log';
        file_put_contents($file,$content,FILE_APPEND);
    }
}
